﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Terraria.Utilities
{
	// Token: 0x020000D8 RID: 216
	public class WeightedRandom<T>
	{
		// Token: 0x06000B02 RID: 2818 RVA: 0x0000BAC4 File Offset: 0x00009CC4
		public WeightedRandom()
		{
			this.random = new UnifiedRandom();
		}

		// Token: 0x06000B03 RID: 2819 RVA: 0x0000BAE9 File Offset: 0x00009CE9
		public WeightedRandom(int seed)
		{
			this.random = new UnifiedRandom(seed);
		}

		// Token: 0x06000B04 RID: 2820 RVA: 0x0000BB0F File Offset: 0x00009D0F
		public WeightedRandom(UnifiedRandom random)
		{
			this.random = random;
		}

		// Token: 0x06000B05 RID: 2821 RVA: 0x0000BB30 File Offset: 0x00009D30
		public WeightedRandom(params Tuple<T, double>[] theElements)
		{
			this.random = new UnifiedRandom();
			this.elements = theElements.ToList<Tuple<T, double>>();
		}

		// Token: 0x06000B06 RID: 2822 RVA: 0x0000BB61 File Offset: 0x00009D61
		public WeightedRandom(int seed, params Tuple<T, double>[] theElements)
		{
			this.random = new UnifiedRandom(seed);
			this.elements = theElements.ToList<Tuple<T, double>>();
		}

		// Token: 0x06000B07 RID: 2823 RVA: 0x0000BB93 File Offset: 0x00009D93
		public WeightedRandom(UnifiedRandom random, params Tuple<T, double>[] theElements)
		{
			this.random = random;
			this.elements = theElements.ToList<Tuple<T, double>>();
		}

		// Token: 0x06000B08 RID: 2824 RVA: 0x0000BBC0 File Offset: 0x00009DC0
		public void Add(T element, double weight = 1.0)
		{
			this.elements.Add(new Tuple<T, double>(element, weight));
			this.needsRefresh = true;
		}

		// Token: 0x06000B09 RID: 2825 RVA: 0x003E7B88 File Offset: 0x003E5D88
		public T Get()
		{
			if (this.needsRefresh)
			{
				this.CalculateTotalWeight();
			}
			double num = this.random.NextDouble();
			num *= this._totalWeight;
			foreach (Tuple<T, double> tuple in this.elements)
			{
				if (num <= tuple.Item2)
				{
					return tuple.Item1;
				}
				num -= tuple.Item2;
			}
			return default(T);
		}

		// Token: 0x06000B0A RID: 2826 RVA: 0x003E7C20 File Offset: 0x003E5E20
		public void CalculateTotalWeight()
		{
			this._totalWeight = 0.0;
			foreach (Tuple<T, double> tuple in this.elements)
			{
				this._totalWeight += tuple.Item2;
			}
			this.needsRefresh = false;
		}

		// Token: 0x06000B0B RID: 2827 RVA: 0x0000BBDB File Offset: 0x00009DDB
		public void Clear()
		{
			this.elements.Clear();
		}

		// Token: 0x06000B0C RID: 2828 RVA: 0x0000BBE8 File Offset: 0x00009DE8
		public static implicit operator T(WeightedRandom<T> weightedRandom)
		{
			return weightedRandom.Get();
		}

		// Token: 0x04000F53 RID: 3923
		public readonly List<Tuple<T, double>> elements = new List<Tuple<T, double>>();

		// Token: 0x04000F54 RID: 3924
		public readonly UnifiedRandom random;

		// Token: 0x04000F55 RID: 3925
		public bool needsRefresh = true;

		// Token: 0x04000F56 RID: 3926
		private double _totalWeight;
	}
}
